package ch.headshot.photomap.client.editor.view;

import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.control.LargeMapControl;
import com.google.gwt.maps.client.control.MapTypeControl;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.geom.LatLngBounds;
import com.google.gwt.user.client.ui.Composite;

public class Map extends Composite {

	private static Map instance;
	private MapWidget map;

	private Map() {
		initWidget(getMap());
	}

	private MapWidget getMap() {
		if (map == null) {
			map = new MapWidget();
			map.setSize("1024px", "768px");
			map.setZoomLevel(10);
			map.setCenter(LatLng.newInstance(46.294369698, 7.836320400));
			map.setInfoWindowEnabled(true);

			// Add some controls for the zoom level
			map.addControl(new LargeMapControl());
			map.addControl(new MapTypeControl());
		}

		return map;
	}

	public void showSegments(Segment[] segments) {
		for (int i = 0; i < segments.length; i++) {
			segments[i].addToMap(map);
		}
	}

	public void hideSegments(Segment[] segments) {
		for (int i = 0; i < segments.length; i++) {
			segments[i].removeFromMap(map);
		}
	}

	public void clear() {
		map.clearOverlays();
	}

	public static Map getInstance() {
		if (instance == null) {
			instance = new Map();
		}
		return instance;
	}

	public void center(Double latmax, Double lonmax, Double latmin, Double lonmin) {
		getMap().setCenter(LatLng.newInstance((latmax + latmin) / 2, (lonmax + lonmin) / 2));
		int boundsZoomLevel = getMap().getBoundsZoomLevel(LatLngBounds.newInstance(LatLng.newInstance(latmin, lonmin), LatLng.newInstance(latmax, lonmax)));
		getMap().setZoomLevel(boundsZoomLevel);
	}
}
